import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_base/common/dialog.dart';
import 'package:flutter_base/common/fun.dart';
import 'package:flutter_base/common/log.dart';

/// Create： Zhang 3/19/21 9:33 AM
/// 描述：网络请求

class Http {
  static final Dio _dio = Dio()
    //添加打印日志的拦截器
    ..interceptors.add(LogInterceptor(
      responseBody: true,
      requestBody: true,
      requestHeader: false,
      responseHeader: false,
    ));

  ///请求参数配置，网关配置信息，根据不同的项目进行自定义配置配置
  static Options _options() => Options(
        method: "POST",
        sendTimeout: 60000,
        receiveTimeout: 60000,
        contentType: "application/otcet-stream",
        headers: {
          "Cookie": "",
          "LOP-DN": "",
          "AppParams": json.encode({}),
        },
      );

  ///上传图片参数
  static Options _uploadOptions() => Options(
        method: 'POST',
        sendTimeout: 60000,
        receiveTimeout: 60000,
        contentType: "application/otcet-stream",
        headers: {
          "Cookie": "",
          "LOP-DN": "",
          "clientinfo": json.encode({
            'appName': '',
            'build': '',
            'client': 'android',
            'clientVersion': '',
            'networkType': '',
            'osVersion': '',
            'partner': '',
            'screen': '',
            'uuid': '',
          }),
          "bucket": "",
          "AppParams": json.encode({}),
        },
      );

  ///上传文件
  ///pics文件路径集合
  static void uploadFile({
    required List<String> pics,
    required Callback<Map<String, dynamic>> suc,
    required Callback<String> fail,
  }) async {
    Map<String, dynamic> file = {};

    for (String s in pics) {
      file["file_${DateTime.now().millisecondsSinceEpoch}"] =
          await MultipartFile.fromFile(s);
    }

    FormData formData = FormData.fromMap(file);
    var response = await _dio.request(
      "", //服务器地址
      data: formData,
      options: _uploadOptions(),
    );
    try {
      if (response.statusCode == 200) {
        final Map<String, dynamic> receivedData = response.data;
        if (receivedData["code"] == 1) {
          suc(receivedData);
        } else {
          fail(receivedData["msg"]);
        }
      } else {
        fail("网络错误");
      }
    } catch (e) {
      Log.d("异常捕获", e.toString());
      fail("数据错误");
    }
  }

  ///get请求
  static void get(
    String url, {
    Map<String, dynamic>? parameters,
    CancelToken? cancelToken,
    required Callback<dynamic>? fail,
    required Callback<dynamic>? suc,
  }) async {
    var response = await _dio.get(
      url,
      queryParameters: parameters,
      cancelToken: cancelToken,
    );

    ///结果回调
    if (response.statusCode != null && response.statusCode == 200) {
      if (suc != null) suc(response.data);
    } else {
      if (fail != null) fail("数据获取异常");
    }
  }

  ///post请求
  static void post(
    String url, {
    Map<String, dynamic>? parameters,
    CancelToken? cancelToken,
    required Callback<dynamic>? fail,
    required Callback<dynamic>? suc,
  }) async {
    var response = await _dio.post(
      url,
      queryParameters: parameters,
      cancelToken: cancelToken,
    );

    ///结果回调
    if (response.statusCode != null && response.statusCode == 200) {
      if (suc != null) suc(response.data);
    } else {
      if (fail != null) fail("请求code:${response.statusCode.toString()}");
    }
  }

  ///使用网关请求数据
  static request(
    String url, {
    data,
    Callback<dynamic>? fail,
    required Callback<dynamic>? suc,
  }) async {
    var response = await _dio.request(
      url,
      //入参编码为json
      data: jsonEncode([data]),
      options: _options(),
    );

    ///结果回调,根据项目返回的数据接口做调整
    try {
      if (response.statusCode != null && response.statusCode == 200) {
        //把返回的数据Decode为Map集合
        final Map<String, dynamic> receivedData =
            jsonDecode(response.data.toString());
        //请求成功码
        if (receivedData["code"] != null && receivedData["code"] == 1) {
          if (suc != null) suc(receivedData["data"]);
        } else {
          if (fail != null) {
            //失败,如果传递了fail方法走方法
            fail(receivedData["msg"] ?? "数据错误");
          } else {
            //否则弹框提示
            toastError(receivedData["msg"] ?? "数据错误");
          }
        }
      } else {
        //发生网络请求错误
        if (fail != null) {
          fail(response.statusCode.toString());
        } else {
          toastError(response.statusCode.toString());
        }
      }
    } catch (e) {
      if (fail != null) {
        fail("数据解析失败");
      } else {
        toastError("数据解析失败");
      }
      Log.d("异常捕获", e.toString());
    }
  }

  ///get请求返回Future
  static Future<Response<T>> getData<T>(String url,
      {Map<String, dynamic>? parameters}) {
    return _dio.get(url, queryParameters: parameters);
  }

  ///post请求返回Future
  static Future<Response<T>> postData<T>(String url,
      {Map<String, dynamic>? parameters}) {
    return _dio.post(url, queryParameters: parameters);
  }
}
